const express = require('express');
const router = express.Router();
const rds = require('../rds');
const logger = require('../logger');

// 商户列表页面
router.get('/', async (req, res) => {
    try {
        // 获取所有商户
        const [merchants] = await rds.query(`
            SELECT * FROM eb_settlement_merchants 
            ORDER BY id DESC
        `);

        // 为每个商户获取渠道信息
        for (const merchant of merchants) {
            const [channels] = await rds.query(`
                SELECT 
                    r.channel_uid as uid,
                    COALESCE(u.real_name, '') as name
                FROM eb_channel_merchant_relations r
                LEFT JOIN eb_user u ON r.channel_uid = u.uid
                WHERE r.merchant_id = ?
            `, [merchant.id]);

            merchant.bound_channels = channels;
        }

        res.render('merchant/list', { 
            merchants,
            title: '商户管理',
            description: '管理结算商户信息'
        });
    } catch (error) {
        logger.error('Error fetching merchants:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取商户列表失败',
            description: error.message
        });
    }
});

// 获取商户详情
router.get('/api/:id', async (req, res) => {
    try {
        const [merchants] = await rds.query(
            'SELECT * FROM eb_settlement_merchants WHERE id = ?', 
            [req.params.id]
        );
        if (merchants.length > 0) {
            res.json(merchants[0]);
        } else {
            res.status(404).json({ error: '商户不存在' });
        }
    } catch (error) {
        logger.error('Error:', error);
        res.status(500).json({ error: error.message });
    }
});

// 获取商户历史记录
router.get('/api/:id/history', async (req, res) => {
    try {
        const [history] = await rds.query(`
            SELECT 
                h.*,
                u.real_name as operator_name,
                DATE_FORMAT(h.created_at, '%Y-%m-%d %H:%i') as created_at,
                CASE h.operation_type
                    WHEN 'bind' THEN CONCAT('绑定渠道 [', h.channel_uid, ']')
                    WHEN 'unbind' THEN CONCAT('解绑渠道 [', h.channel_uid, ']')
                    WHEN 'delete' THEN '删除商户'
                    WHEN 'update' THEN '更新商户信息'
                    WHEN 'create' THEN '创建商户'
                    ELSE h.operation_type
                END as operation_type,
                CASE 
                    WHEN h.operation_type IN ('bind', 'unbind') THEN (
                        SELECT real_name 
                        FROM eb_user 
                        WHERE uid = h.channel_uid
                    )
                    ELSE NULL
                END as channel_name,
            FROM eb_channel_merchant_history h
            LEFT JOIN eb_user u ON h.operator_uid = u.uid
            WHERE h.merchant_id = ?
            ORDER BY h.created_at DESC
        `, [req.params.id]);

        res.json(history);
    } catch (error) {
        logger.error('Error fetching merchant history:', error);
        res.status(500).json({ error: error.message });
    }
});

// API路由
router.post('/api', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        const {
            merchant_id,
            merchant_name,
            payment_key,
            cert_path = '',
            key_path = ''
        } = req.body;

        // 验证必填字段
        if (!merchant_id || !merchant_name || !payment_key) {
            throw new Error('商户号、商户名称和支付密钥为必填项');
        }

        // 检查商户号是否已存在
        const [existing] = await connection.query(
            'SELECT 1 FROM eb_settlement_merchants WHERE merchant_id = ?',
            [merchant_id]
        );

        if (existing.length > 0) {
            throw new Error('商户号已存在');
        }

        // 插入新商户
        const [result] = await connection.query(
            `INSERT INTO eb_settlement_merchants 
            (merchant_id, merchant_name, payment_key, cert_path, key_path)
            VALUES (?, ?, ?, ?, ?)`,
            [merchant_id, merchant_name, payment_key, cert_path, key_path]
        );

        // 记录创建历史
        await connection.query(
            'INSERT INTO eb_channel_merchant_history (channel_uid, merchant_id, operator_uid, operation_type, remark) VALUES (?, ?, ?, ?, ?)',
            [0, result.insertId, req.session.totemUID, 'create', `创建商户号: ${merchant_id}`]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error creating merchant:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

router.put('/api/:id', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        const {
            merchant_name,
            payment_key,
            cert_path = '',
            key_path = ''
        } = req.body;

        // 验证必填字段
        if (!merchant_name || !payment_key) {
            throw new Error('商户名称和支付密钥为必填项');
        }

        // 更新商户信息
        await connection.query(
            `UPDATE eb_settlement_merchants 
            SET merchant_name = ?, payment_key = ?, cert_path = ?, key_path = ?
            WHERE id = ?`,
            [merchant_name, payment_key, cert_path, key_path, req.params.id]
        );

        // 记录更新历史
        await connection.query(
            'INSERT INTO eb_channel_merchant_history (channel_uid, merchant_id, operator_uid, operation_type, remark) VALUES (?, ?, ?, ?, ?)',
            [0, req.params.id, req.session.totemUID, 'update', `更新商户名称为: ${merchant_name}`]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error updating merchant:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

// 删除商户
router.delete('/api/:id', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        // 检查是否有渠道绑定
        const [boundChannels] = await connection.query(
            'SELECT channel_uid FROM eb_channel_merchant_relations WHERE merchant_id = ?',
            [req.params.id]
        );

        if (boundChannels.length > 0) {
            throw new Error('该商户还有绑定的渠道，请先解除绑定');
        }

        // 检查是否为默认商户
        const [defaultCheck] = await connection.query(
            'SELECT is_default FROM eb_settlement_merchants WHERE id = ?',
            [req.params.id]
        );

        if (defaultCheck.length > 0 && defaultCheck[0].is_default) {
            throw new Error('不能删除默认商户');
        }

        // 记录删除操作历史
        await connection.query(
            'INSERT INTO eb_channel_merchant_history (channel_uid, merchant_id, operator_uid, operation_type, remark) VALUES (?, ?, ?, ?, ?)',
            [0, req.params.id, req.session.totemUID, 'delete', '删除商户及其所有关联信息']
        );

        // 删除商户
        await connection.query(
            'DELETE FROM eb_settlement_merchants WHERE id = ?', 
            [req.params.id]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error deleting merchant:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

// 设置默认商户
router.put('/api/:id/default', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        // 先清除所有默认标记
        await connection.query(
            'UPDATE eb_settlement_merchants SET is_default = 0'
        );

        // 设置新的默认商户
        await connection.query(
            'UPDATE eb_settlement_merchants SET is_default = 1 WHERE id = ?',
            [req.params.id]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error setting default merchant:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

// 渠道相关API
router.get('/api/:id/channel/:uid/history', async (req, res) => {
    try {
        const [channelInfo] = await rds.query(`
            SELECT uid, real_name, agency
            FROM eb_user
            WHERE uid = ?
        `, [req.params.uid]);

        if (channelInfo.length === 0) {
            return res.status(404).json({ error: '渠道不存在' });
        }

        const [history] = await rds.query(`
            SELECT h.*, 
                   DATE_FORMAT(h.created_at, '%Y-%m-%d %H:%i:%s') as created_at,
                   u.real_name as operator_name
            FROM eb_channel_merchant_history h
            LEFT JOIN eb_user u ON h.operator_uid = u.uid
            WHERE h.channel_uid = ?
            AND h.merchant_id = ?
            ORDER BY h.created_at DESC
        `, [req.params.uid, req.params.id]);

        const [currentBinding] = await rds.query(`
            SELECT 1 as is_bound
            FROM eb_channel_merchant_relations
            WHERE channel_uid = ? AND merchant_id = ?
        `, [req.params.uid, req.params.id]);

        res.json({
            channel: channelInfo[0],
            history: history,
            is_bound: currentBinding.length > 0
        });
    } catch (error) {
        logger.error('Error fetching channel history:', error);
        res.status(500).json({ error: error.message });
    }
});

// 绑定渠道
router.post('/api/:id/channel/:uid', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        // 检查渠道是否已绑定
        const [existing] = await connection.query(
            'SELECT merchant_id FROM eb_channel_merchant_relations WHERE channel_uid = ?',
            [req.params.uid]
        );

        if (existing.length > 0) {
            throw new Error('该渠道已绑定到其他商户');
        }

        // 创建绑定关系
        await connection.query(
            'INSERT INTO eb_channel_merchant_relations (channel_uid, merchant_id) VALUES (?, ?)',
            [req.params.uid, req.params.id]
        );

        // 记录操作历史
        await connection.query(
            'INSERT INTO eb_channel_merchant_history (channel_uid, merchant_id, operator_uid, operation_type, remark) VALUES (?, ?, ?, ?, ?)',
            [req.params.uid, req.params.id, req.session.totemUID, 'bind', `绑定渠道 [${req.params.uid}]`]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error binding channel:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

// 解除渠道绑定
router.delete('/api/:id/channel/:uid', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        const [existingBinding] = await connection.query(
            'SELECT 1 FROM eb_channel_merchant_relations WHERE channel_uid = ? AND merchant_id = ?',
            [req.params.uid, req.params.id]
        );

        if (existingBinding.length === 0) {
            await connection.rollback();
            return res.status(404).json({ error: '未找到有效的绑定关系' });
        }

        await connection.query(
            'DELETE FROM eb_channel_merchant_relations WHERE channel_uid = ? AND merchant_id = ?',
            [req.params.uid, req.params.id]
        );

        await connection.query(
            'INSERT INTO eb_channel_merchant_history (channel_uid, merchant_id, operator_uid, operation_type, remark) VALUES (?, ?, ?, ?, ?)',
            [req.params.uid, req.params.id, req.session.totemUID, 'unbind', `解绑渠道 [${req.params.uid}]`]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error unbinding channel:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

// 编辑商户页面
router.get('/edit/:id', async (req, res) => {
    try {
        const [merchants] = await rds.query(
            'SELECT * FROM eb_settlement_merchants WHERE id = ?',
            [req.params.id]
        );

        if (merchants.length === 0) {
            return res.status(404).render('warn', {
                title: '商户不存在',
                message: '未找到该商户',
                description: `商户ID: ${req.params.id}`
            });
        }

        res.render('merchant/edit', {
            merchant: merchants[0],
            title: '编辑商户',
            description: `商户ID: ${req.params.id}`
        });
    } catch (error) {
        logger.error('Error fetching merchant:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取商户详情失败',
            description: error.message
        });
    }
});

// 查看商户历史
router.get('/history/:id', async (req, res) => {
    try {
        const [history] = await rds.query(`
            SELECT 
                h.*,
                u.real_name as operator_name,
                DATE_FORMAT(h.created_at, '%Y-%m-%d %H:%i') as created_at
            FROM eb_channel_merchant_history h
            LEFT JOIN eb_user u ON h.operator_uid = u.uid
            WHERE h.merchant_id = ?
            ORDER BY h.created_at DESC
        `, [req.params.id]);

        res.render('merchant/history', {
            history,
            title: '商户历史',
            description: `商户ID: ${req.params.id}`
        });
    } catch (error) {
        logger.error('Error fetching merchant history:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取商户历史失败',
            description: error.message
        });
    }
});

module.exports = router; 
